<template>
    <div>
        <slot></slot>
    </div>
</template>

<script>
    export default {
        name:'my-form',
        props: {
            mode: {
                type: Object,
                default: () => ({})
            },
            rule: {
                type: Object,
                default: () => ({})
            }
        },
        methods: {
            validate() {
                const rules = Object.keys(this.rule);
                let message = "";
                for(let i = 0; i < rules.length; i++) {
                    const key = rules[i];
                    const rule = this.rule[key];
                    const value = this.mode[key];
                    rule.forEach(item => {
                        if(!this.check(value, item) && message == "") {
                            message = item.message;
                        }
                    });
                    if(message != "") {
                        break;
                    }
                }    
                if(message) {
                    this.$message.error(message);
                } 
                return message === "" ? Promise.resolve() : Promise.reject()
            },
            check(val, rule) {
                if(rule.required) {
                    return val != "";
                } else if(rule.min) {
                    return val.length >= rule.min
                } else if (rule.max) {
                    return val.length <= rule.min;
                } else if (rule.reg) {
                    return rule.reg.test(val);
                }
            }
        },
    }
</script>

<style lang="scss" scoped>

</style>